package pro.cherish.smartfile.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import pro.cherish.smartfile.mapper.AttachmentMapper;
import pro.cherish.smartfile.module.entity.Attachment;
import pro.cherish.smartfile.service.AttachmentService;

import java.util.List;

/**
 * @author 创建人：lys
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2020-12-04 lys 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：AttachmentServiceImpl
 * @Description 功能说明：
 * <p>
 *
 * </p>
 * **********************************************************************
 * @date 创建日期： 2020-12-04 lys
 */
@Service
@Slf4j
public class AttachmentServiceImpl extends ServiceImpl<AttachmentMapper, Attachment> implements AttachmentService {
    @Override
    public void saveAttachment(Attachment attachment) {
        String fileMd5 = attachment.getFileMd5();
        if (exist(fileMd5)) {
            log.error("文件MD5[{}]已经存在，不可重复插入", attachment.getFileMd5());
            return;
        }
        this.baseMapper.insert(attachment);
    }

    @Override
    public Boolean exist(String identify) {
        QueryWrapper<Attachment> qw = new QueryWrapper<>();
        qw.lambda().eq(Attachment::getFileMd5, identify);
        List<Attachment> attachments = this.baseMapper.selectList(qw);
        return CollUtil.isNotEmpty(attachments);
    }

    @Override
    public IPage<Attachment> queryMyUploads(IPage<Attachment> page, String userId) {
        QueryWrapper<Attachment> qw = new QueryWrapper<>();
        qw.lambda().eq(Attachment::getCreateUser, userId);
        return this.baseMapper.selectPage(page, qw);
    }

    @Override
    public Attachment queryFile(String id) {
        QueryWrapper<Attachment> qw = new QueryWrapper<>();
        qw.lambda().eq(Attachment::getFileMd5, id);
        List<Attachment> attachments = this.baseMapper.selectList(qw);
        if (CollUtil.isNotEmpty(attachments)) {
            if (attachments.size() > 1) {
                log.error("本该只存在一个md5值[{}]对应db文件记录，出现脏数据", id);
            }
            return attachments.get(0);
        }
        return null;
    }

    @Override
    public void removeAttachment(String identify) {
        UpdateWrapper<Attachment> qw = new UpdateWrapper<>();
        qw.lambda().eq(Attachment::getFileMd5, identify);
        this.baseMapper.delete(qw);
    }
}
